package com.zhu.blog.controller;


import com.zhu.blog.model.Comment;
import com.zhu.blog.model.User;
import com.zhu.blog.service.BlogService;
import com.zhu.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


/**
*博客评论
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @Value("${admin.openid}")
    private String adminOpenid;

    //根据博客id获取要评论某个博客评论内容列表
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }

    //提交评论
    @RequestMapping(value = "/comments",method = RequestMethod.POST)
    public String post(Comment comment, HttpSession session){
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        String loginStatus = (String) session.getAttribute("loginStatus");
        //判断当前的登录状态是否是QQ或GitHub
        if(loginStatus != null){
            String avatar = (String) session.getAttribute("avatar");
            String openid = (String) session.getAttribute("openid");
            comment.setAvatar(avatar);
            comment.setAdminComment(1);
            //判断是否管理员评论
            if(adminOpenid.equals(openid)){
                comment.setAdminComment(2);
            }
        }else {
            comment.setAvatar(avatar);
            comment.setAdminComment(0);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }
}
